package com.youlai.boot.system.excel;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.youlai.boot.common.excel.ExcelDataHandler;
import com.youlai.boot.common.excel.ExcelHandlerType;
import com.youlai.boot.common.result.ExcelResult;
import com.youlai.boot.system.converter.DailySalesReportConverter;
import com.youlai.boot.system.model.dto.DailySalesReportExcelDTO;
import com.youlai.boot.system.model.entity.DailySalesReport;
import com.youlai.boot.system.model.query.DailySalesReportQuery;
import com.youlai.boot.system.service.DailySalesReportService;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;

import java.time.LocalDate;
import java.time.format.DateTimeFormatter;
import java.util.List;
import java.util.Map;

/**
 * 日报数据Excel处理器
 *
 * @author xiheforever
 * @since 2025-06-03
 */
@Component
@ExcelHandlerType("daily-sales-report")
@RequiredArgsConstructor
@Slf4j
public class DailySalesReportExcelHandler implements ExcelDataHandler<DailySalesReportExcelDTO> {

    private final DailySalesReportService dailySalesReportService;
    private final DailySalesReportConverter dailySalesReportConverter;

    @Override
    public Class<DailySalesReportExcelDTO> getEntityClass() {
        return DailySalesReportExcelDTO.class;
    }

    @Override
    public String getFileName() {
        return "日报数据_" + LocalDate.now().format(DateTimeFormatter.ofPattern("yyyyMMdd"));
    }

    @Override
    public String getSheetName() {
        return "日报数据";
    }

    @Override
    @SuppressWarnings("unchecked")
    public List<DailySalesReportExcelDTO> getExportData(Object query) {
        List<DailySalesReport> reportList;
        LambdaQueryWrapper<DailySalesReport> queryWrapper = new LambdaQueryWrapper<>();
        
        // 指定要查询的字段，排除不需要的字段
        queryWrapper.select(DailySalesReport.class, tableFieldInfo -> 
            !"create_time".equals(tableFieldInfo.getColumn()) && 
            !"update_time".equals(tableFieldInfo.getColumn()) &&
            !"is_deleted".equals(tableFieldInfo.getColumn())
        );
        
        if (query instanceof Map) {
            // 处理Map类型的查询参数
            Map<String, Object> params = (Map<String, Object>) query;
            
            // 添加日期范围条件
            if (params.containsKey("startDate") && StringUtils.hasText((String) params.get("startDate"))) {
                LocalDate startDate = LocalDate.parse((String) params.get("startDate"));
                queryWrapper.ge(DailySalesReport::getReportDate, startDate);
            }
            if (params.containsKey("endDate") && StringUtils.hasText((String) params.get("endDate"))) {
                LocalDate endDate = LocalDate.parse((String) params.get("endDate"));
                queryWrapper.le(DailySalesReport::getReportDate, endDate);
            }
        } else if (query instanceof DailySalesReportQuery pageQuery) {
            // 处理DailySalesReportQuery类型的查询参数
            if (pageQuery.getReportDate() != null && !pageQuery.getReportDate().isEmpty()) {
                // 处理日期范围查询，假设传入的是 [startDate, endDate] 格式
                if (pageQuery.getReportDate().size() >= 1 && StringUtils.hasText(pageQuery.getReportDate().get(0))) {
                    LocalDate startDate = LocalDate.parse(pageQuery.getReportDate().get(0));
                    queryWrapper.ge(DailySalesReport::getReportDate, startDate);
                }
                if (pageQuery.getReportDate().size() >= 2 && StringUtils.hasText(pageQuery.getReportDate().get(1))) {
                    LocalDate endDate = LocalDate.parse(pageQuery.getReportDate().get(1));
                    queryWrapper.le(DailySalesReport::getReportDate, endDate);
                }
            }
        }
        
        // 按日期降序排列
        queryWrapper.orderByDesc(DailySalesReport::getReportDate);
        
        // 获取数据列表（不分页）
        reportList = dailySalesReportService.list(queryWrapper);
        
        // 转换为Excel数据模型
        return dailySalesReportConverter.entity2ExcelDTO(reportList);
    }

    @Override
    public void handleImportData(List<DailySalesReportExcelDTO> dataList, ExcelResult result) {
        log.info("开始导入日报数据，共{}条记录", dataList.size());
        
        // 数据校验和处理
        for (DailySalesReportExcelDTO dto : dataList) {
            try {
                // 数据验证
                validateData(dto);
                
                // 检查是否已存在相同日期的数据
                LambdaQueryWrapper<DailySalesReport> existQuery = new LambdaQueryWrapper<>();
                existQuery.eq(DailySalesReport::getReportDate, dto.getReportDate());
                DailySalesReport existingReport = dailySalesReportService.getOne(existQuery);
                
                // 转换为实体
                DailySalesReport report = dailySalesReportConverter.excelDTO2Entity(dto);
                log.debug("转换后的实体数据: {}", report);
                
                boolean saved;
                if (existingReport != null) {
                    // 如果已存在，更新数据
                    report.setId(existingReport.getId());
                    saved = dailySalesReportService.updateById(report);
                    log.debug("更新日期{}的数据: {}", dto.getReportDate(), saved ? "成功" : "失败");
                } else {
                    // 如果不存在，新增数据
                    saved = dailySalesReportService.save(report);
                    log.debug("新增日期{}的数据: {}", dto.getReportDate(), saved ? "成功" : "失败");
                }
                
                if (saved) {
                    // 成功计数
                    result.setValidCount(result.getValidCount() + 1);
                    log.debug("成功处理第{}条数据", result.getValidCount());
                } else {
                    // 失败计数和错误信息
                    result.setInvalidCount(result.getInvalidCount() + 1);
                    String errorMsg = "第" + (result.getValidCount() + result.getInvalidCount()) + "行: 保存失败";
                    result.addErrorMsg(errorMsg);
                    log.error(errorMsg);
                }
            } catch (Exception e) {
                // 失败计数和错误信息
                result.setInvalidCount(result.getInvalidCount() + 1);
                String errorMsg = "第" + (result.getValidCount() + result.getInvalidCount()) + "行: " + e.getMessage();
                result.addErrorMsg(errorMsg);
                log.error("导入日报数据错误: {}", errorMsg, e);
            }
        }
        
        // 设置导入结果
        result.setSuccess(result.getInvalidCount() == 0);
        log.info("日报数据导入完成，成功{}条，失败{}条", result.getValidCount(), result.getInvalidCount());
    }
    
    /**
     * 数据验证
     *
     * @param dto 数据对象
     */
    private void validateData(DailySalesReportExcelDTO dto) {
        // 报告日期必填
        if (dto.getReportDate() == null) {
            throw new IllegalArgumentException("报告日期不能为空");
        }
        
        // 客单价必填且大于0
        if (dto.getAverageTransactionValue() == null || dto.getAverageTransactionValue().compareTo(java.math.BigDecimal.ZERO) <= 0) {
            throw new IllegalArgumentException("客单价不能为空且必须大于0");
        }
        
        // 转化率必填且在0-1之间
        if (dto.getConversionRate() == null || dto.getConversionRate().compareTo(java.math.BigDecimal.ZERO) < 0 || 
            dto.getConversionRate().compareTo(java.math.BigDecimal.ONE) > 0) {
            throw new IllegalArgumentException("转化率不能为空且必须在0-100%之间");
        }
        
        // 月度销售任务必填且大于0
        if (dto.getMonthlySalesTarget() == null || dto.getMonthlySalesTarget().compareTo(java.math.BigDecimal.ZERO) <= 0) {
            throw new IllegalArgumentException("月度销售任务不能为空且必须大于0");
        }
        
        // 已完成销售额必填且大于等于0
        if (dto.getCurrentSalesAmount() == null || dto.getCurrentSalesAmount().compareTo(java.math.BigDecimal.ZERO) < 0) {
            throw new IllegalArgumentException("已完成销售额不能为空且必须大于等于0");
        }
        
        // 其他业务验证规则
        // ...
    }
    
    @Override
    public List<DailySalesReportExcelDTO> getTemplateData() {
        // 返回模板数据（空或示例数据）
        return List.of();
    }
} 